<template>
  <div class="app-container">
    <el-button type="primary"
      icon="el-icon-plus"
      @click="handleAdd"
      v-hasPermi="['api:scheme:add']"
      class="ml20">新增</el-button>

    <div class="container-box"
      v-loading="loading">
      <div class="tab-box">
        <el-tabs tab-position="left"
          type="card"
          closable
          v-model="activeId"
          @tab-remove="handleDelete">
          <el-tab-pane :label="item.schemeName"
            :name="item.id"
            v-for="item in schemeList"
            :key="item.id"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="section-box">
        <div class="section-title">基本信息</div>
        <el-row v-hasPermi="['api:scheme:edit']"
          style="display: flex; justify-content: flex-end">
          <el-button type="warning"
            icon="el-icon-edit"
            @click="handleToEdit(1)"
            class="mb10"
            v-if="!isEdit">编辑</el-button>
          <template v-else>
            <el-button v-if="!isAdd"
              type="info"
              icon="el-icon-check"
              @click="handleToEdit(0)"
              class="mb10">取消编辑</el-button>
            <el-button type="danger"
              icon="el-icon-check"
              @click="submitForm"
              class="mb10">保存</el-button>
          </template>
        </el-row>
        <el-form ref="form"
          :model="form"
          :rules="rules"
          label-width="150px"
          class="form-box">
          <el-form-item label="分配方案名称"
            prop="schemeName">
            <span v-if="!isEdit">{{ form.schemeName }}</span>
            <el-input v-else
              v-model="form.schemeName"
              placeholder="请输入分配方案名称"
              style="width: 500px" />
          </el-form-item>
          <el-form-item label="返利类型"
            prop="schemeType">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_scheme_type"
                :value="form.schemeType" />
            </span>
            <el-select v-else
              v-model="form.schemeType"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_scheme_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分佣计算方式"
            prop="calcType">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_calc_type"
                :value="form.calcType" />
            </span>
            <el-select v-else
              v-model="form.calcType"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_calc_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="方案整体分成比例"
            prop="tscale">
            <span v-if="!isEdit">{{ form.tscale }}</span>
            <el-input v-else
              v-model="form.tscale"
              placeholder="请输入方案整体分成比例"
              style="width: 500px" />
          </el-form-item>
          <el-form-item label="佣金计算输入"
            prop="calcField">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_calc_field"
                :value="form.calcField" />
            </span>
            <el-select v-else
              v-model="form.calcField"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_calc_field"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="关联商品"
            prop="pdcScope">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_pdc_scope"
                :value="form.pdcScope" />
            </span>
            <el-select v-else
              v-model="form.pdcScope"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_pdc_scope"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="交易支付方式"
            prop="payType">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_pay_type"
                :value="form.payType" />
            </span>
            <el-select v-else
              v-model="form.payType"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_pay_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="返佣是否含客户自己"
            prop="includeSelf">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_include_self"
                :value="form.includeSelf" />
            </span>
            <el-select v-else
              v-model="form.includeSelf"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_include_self"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="首购复购"
            prop="firstTrade">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.agt_first_trade"
                :value="form.firstTrade" />
            </span>
            <el-select v-else
              v-model="form.firstTrade"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.agt_first_trade"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="分佣人数"
            prop="assignCnt">
            <span v-if="!isEdit">{{ form.assignCnt }}</span>
            <el-input v-else
              v-model="form.assignCnt"
              style="width: 500px"
              placeholder="请输入分佣人数" />
          </el-form-item>
          <el-form-item label="是否有效"
            prop="enabled">
            <span v-if="!isEdit">
              <dict-tag :options="dict.type.sys_enabled"
                :value="form.enabled" />
            </span>
            <el-select v-else
              v-model="form.enabled"
              clearable
              placeholder="请选择"
              style="width: 500px">
              <el-option v-for="dict in dict.type.sys_enabled"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label=" 备注"
            prop="remark">
            <span v-if="!isEdit">{{ form.remark }}</span>
            <el-input v-else
              type="textarea"
              v-model="form.remark"
              style="width: 500px"
              placeholder="请输入备注" />
          </el-form-item>
        </el-form>

        <div class="section-title mt20 mb20">方案明细</div>
        <el-row :gutter="10"
          class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"
              plain
              icon="el-icon-plus">新增</el-button>
          </el-col>
        </el-row>
        <el-table :data="agtScmItemList">
          <el-table-column label="方案明细ID"
            align="center"
            prop="id"
            min-width="100" />
          <el-table-column label="收益类别"
            align="center"
            prop="profitType"
            min-width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.profit_type"
                :value="scope.row.profitType" />
            </template>
          </el-table-column>
          <el-table-column label="层级"
            align="center"
            prop="treeLev"
            min-width="100">
            <template slot-scope="scope">
              <dict-tag v-if="scope.row.treeLev !== null"
                :options="dict.type.tree_lev"
                :value="scope.row.treeLev" />
            </template>
          </el-table-column>
          <el-table-column label="会员等级"
            align="center"
            prop="custTypeName"
            min-width="100" />
          <el-table-column label="备注"
            align="center"
            prop="remark"
            min-width="160"
            show-overflow-tooltip />
          <el-table-column label="开始时间"
            align="center"
            prop="beginTime"
            min-width="160" />
          <el-table-column label="结束时间"
            align="center"
            prop="endTime"
            min-width="160" />
          <el-table-column label="创建时间"
            align="center"
            prop="createTime"
            min-width="160" />
          <el-table-column label="更新时间"
            align="center"
            prop="updateTime"
            min-width="160" />
          <el-table-column label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            min-width="120">
            <template slot-scope="scope">
              <el-button size="mini"
                type="text"
                icon="el-icon-edit">修改</el-button>
              <el-button size="mini"
                type="text"
                icon="el-icon-delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="section-title mt20 mb20">商品信息</div>
        <el-row :gutter="10"
          class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"
              plain
              icon="el-icon-plus">新增</el-button>
          </el-col>
        </el-row>
        <el-table :data="agtScmProdList">
          <el-table-column label="记录ID"
            align="center"
            prop="id"
            min-width="100" />
          <el-table-column label="商品id/充值id/优惠券ID"
            align="center"
            prop="pdcId"
            min-width="200" />
          <el-table-column label="商品/充值名称/优惠券"
            align="center"
            prop="pdcName"
            min-width="200" />
          <el-table-column label="类别"
            align="center"
            prop="pdcType"
            min-width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pdc_type"
                :value="scope.row.pdcType" />
            </template>
          </el-table-column>
          <el-table-column label="备注"
            align="center"
            prop="remark"
            min-width="160"
            show-overflow-tooltip />
          <el-table-column label="开始时间"
            align="center"
            prop="beginTime"
            min-width="160" />
          <el-table-column label="结束时间"
            align="center"
            prop="endTime"
            min-width="160" />
          <el-table-column label="创建时间"
            align="center"
            prop="createTime"
            min-width="160" />
          <el-table-column label="更新时间"
            align="center"
            prop="updateTime"
            min-width="160" />
          <el-table-column label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            min-width="120">
            <template slot-scope="scope">
              <el-button size="mini"
                type="text"
                icon="el-icon-edit">修改</el-button>
              <el-button size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteProd(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>

    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import {
  listScheme,
  getScheme,
  delScheme,
  addScheme,
  updateScheme,
  delSchemeProd
} from "@/api/djk/platformMgr/subcommissionSet";

export default {
  name: "Scheme",
  dicts: [
    "sys_enabled",
    "agt_calc_field",
    "agt_pdc_scope",
    "agt_first_trade",
    "agt_include_self",
    "agt_scheme_type",
    "agt_calc_type",
    "agt_pay_type",
    "profit_type",
    "tree_lev",
    "pdc_type",
  ],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分佣方案配置表格数据
      schemeList: [],
      itemSchemeInfo: "",
      isEdit: false,
      isAdd: false,
      activeId: "",
      agtScmItemList: [],
      agtScmProdList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schemeName: null,
        schemeType: null,
        calcField: null,
        tscale: null,
        calcType: null,
        pdcScope: null,
        payType: null,
        firstTrade: null,
        includeSelf: null,
        assignCnt: null,
        enabled: null,
        createDt: null,
        version: null,
        sysAccount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        schemeName: [
          { required: true, message: "分配方案名称不能为空", trigger: "blur" },
        ],
        schemeType: [
          {
            required: true,
            message: "返佣类别不能为空",
            trigger: "change",
          },
        ],
        calcField: [
          {
            required: true,
            message: "佣金计算输入不能为空",
            trigger: "blur",
          },
        ],
        calcType: [
          {
            required: true,
            message: "分佣计算方式不能为空",
            trigger: "change",
          },
        ],
        pdcScope: [
          {
            required: true,
            message: "关联商品不能为空",
            trigger: "blur",
          },
        ],
        payType: [
          {
            required: true,
            message: "交易支付方式不能为空",
            trigger: "change",
          },
        ],
        firstTrade: [
          {
            required: true,
            message: "首购复购不能为空",
            trigger: "blur",
          },
        ],
        includeSelf: [
          {
            required: true,
            message: "返佣是否含客户自己不能为空",
            trigger: "blur",
          },
        ],
        assignCnt: [
          { required: true, message: "分佣人数不能为空", trigger: "blur" },
        ],
        // createDt: [
        //   { required: true, message: "创建时间不能为空", trigger: "blur" },
        // ],
        // version: [
        //   { required: true, message: "数据更新版本不能为空", trigger: "blur" },
        // ],
      },
    };
  },
  watch: {
    ["form.schemeName"] (val) {
      if (this.isAdd) {
        this.schemeList.forEach((item) => {
          if (item.id == this.activeId) {
            item.schemeName = val;
          }
        });
      }
    },
    activeId (val, oldVal) {
      if (val.indexOf("add") < 0) {
        this.isAdd = false;
        this.isEdit = false;

        if (oldVal.indexOf("add") > -1) {
          this.schemeList.forEach((item) => {
            if (item.id == oldVal) {
              item.apiAgtSchemeVO = JSON.parse(JSON.stringify(this.form));
            }
          });
        }
      } else {
        this.isAdd = true;
        this.isEdit = true;
      }
      setTimeout(() => {
        this.getItemSchemeData(val);
      });
    },
  },
  created () {
    this.getList();
  },
  methods: {
    /** 查询分佣方案配置列表 */
    getList () {
      this.loading = true;
      listScheme(this.queryParams).then((response) => {
        this.schemeList = response.rows;
        this.activeId = this.schemeList[0].id;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      // this.open = false;
      // this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        schemeName: null,
        schemeType: null,
        calcField: null,
        tscale: null,
        calcType: null,
        pdcScope: null,
        payType: null,
        firstTrade: null,
        includeSelf: null,
        assignCnt: null,
        enabled: null,
        // createDt: null,
        // version: null,
        remark: null,
        // sysAccount: null,
      };
      this.agtScmItemList = [];
      this.agtScmProdList = [];
      this.resetForm("form");
    },
    // 获取详情数据
    getItemSchemeData (id) {
      if (!id) return;
      // getScheme(id).then((response) => {
      //   this.itemSchemeInfo = JSON.stringify(response.data);
      //   this.form = response.data;
      //   this.agtScmItemList = response.data.agtScmItemList;
      //   this.agtScmProdList = response.data.agtScmProdList;
      // });
      this.schemeList.forEach((item) => {
        if (item.id == id) {
          let data = JSON.parse(JSON.stringify(item.apiAgtSchemeVO));
          this.itemSchemeInfo = JSON.stringify(item.apiAgtSchemeVO);
          this.form = data;
          this.agtScmItemList = data.agtScmItemList;
          this.agtScmProdList = data.agtScmProdList;
          this.resetForm("form");
        }
      });
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      let addId = "add" + (this.schemeList.length + 1);
      this.schemeList.push({
        id: addId,
        schemeName: null,
        apiAgtSchemeVO: {
          id: addId,
          schemeName: null,
          schemeType: null,
          calcField: null,
          tscale: null,
          calcType: null,
          pdcScope: null,
          payType: null,
          firstTrade: null,
          includeSelf: null,
          assignCnt: null,
          enabled: null,
          remark: null,
          agtScmItemList: [],
          agtScmProdList: [],
        },
      });
      this.isAdd = true;
      this.isEdit = true;
      this.activeId = addId;
    },
    /** 修改按钮操作 */
    handleToEdit (type) {
      this.isEdit = !this.isEdit;
      if (!type) {
        this.form = JSON.parse(this.itemSchemeInfo);
      }
    },
    handleUpdate () {
      // this.reset();
      // const id = row.id || this.ids;
      // getScheme(id).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改分佣方案配置";
      // });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id.indexOf("add") > -1) {
            this.form.id = null;
          }
          if (this.form.id != null) {
            updateScheme(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.isEdit = false;
              this.getList();
            });
          } else {
            addScheme(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.isEdit = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (ids) {
      // const ids = row.id || this.ids;
      if (ids.indexOf("add") < 0) {
        this.$modal
          .confirm('是否确认删除分佣方案配置编号为"' + ids + '"的数据项？')
          .then(function () {
            this.removeTab(ids);
            return delScheme(ids);
          })
          .then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => { });
      } else {
        this.removeTab(ids);
      }
    },
    removeTab (ids) {
      if (this.activeId == ids) {
        let delIdx = null;
        this.schemeList.forEach((item, index) => {
          if (item.id == ids) {
            delIdx = index;
            let nextTab =
              this.schemeList[index + 1] || this.schemeList[index - 1];
            if (nextTab) {
              this.activeId = nextTab.id;
            }
          }
        });

        this.schemeList.splice(delIdx, 1);
      }
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download(
    //     "api/scheme/export",
    //     {
    //       ...this.queryParams,
    //     },
    //     `scheme_${new Date().getTime()}.xlsx`
    //   );
    // },
    handleDeleteProd (row) {
      const ids = row.pdcId;
      this.$modal
        .confirm('是否确认删除商品编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSchemeProd(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>

<style scoped lang="scss">
.app-container {
  width: 100%;
  min-height: 100%;
  background-color: #f9f9f9;
}
.container-box {
  display: flex;
  padding: 20px;
  min-height: 100%;
  .tab-box {
    width: 200px;
    background-color: #fff;
    padding: 20px;
    border-radius: 10px;
    display: flex;
    justify-content: center;
  }
  .section-box {
    flex: 1;
    overflow: hidden;
    margin-left: 40px;
    background-color: #fff;
    border-radius: 10px;
    padding: 20px 40px;
    .section-title {
      font-size: 16px;
      font-weight: bold;
      display: flex;
      align-items: center;
      &:before {
        content: "";
        width: 3px;
        height: 12px;
        border-radius: 1px;
        background-color: #1890ff;
        margin-right: 10px;
      }
    }
  }
  &::v-deep .el-tabs--left.el-tabs--card .el-tabs__nav {
    border: none;
  }
  &::v-deep .el-tabs--left.el-tabs--card .el-tabs__item.is-left {
    border: none;
  }
  &::v-deep .el-tabs--card > .el-tabs__header {
    border: none;
  }
  &::v-deep
    .el-tabs--card
    > .el-tabs__header
    .el-tabs__item.is-active.is-closable {
    background-color: #e8f4ff;
    border-radius: 30px 0 0 30px;
    transition: all 0.3s;
  }
}
</style>
